import { ref, watch,toRefs, isRuntimeOnly} from "vue"
import { useRouter,useRoute } from 'vue-router'
import { getProducts, getProductDetail } from "@/api/products.js"
import {useRequest} from 'vue-request';



export const useProducts = () => {
    //不能修改
    var productList = ref([]);
    const loading = ref(false);
    //接收子组件传过来的筛选条件

    const _filterForm = ref({});
    const pages = ref(1);
    //每页条数
    const pageNum = ref(6);
    //总产品数
    const total = ref(0)
    // const {data:productList,loading,run} = useRequest(getProducts,{manual:true});
    // console.log('request111',data);



    // const {total,data:productList} = data;
    // console.log('总数',total);
    // console.log('data:',productList);
    //监听器：
    watch([pages, _filterForm], async (newVal) => {
        //发送请求
        loading.value = true
        let res = await getProducts({ page: pages.value, pageNum: pageNum.value, ..._filterForm.value }).then(res => res.data);
        productList.value = res.data;
        console.log("筛选结果", res);
        total.value = res.total;
        loading.value = false

        // run({ page: pages.value, pageNum: pageNum.value, ..._filterForm.value });



    }, {
        //创建阶段就执行一次监听的handler
        immediate: true
    })

    const router = useRouter();

    /* getSolarInfo();
    async function getSolarInfo() {
      loading.value = true
      let res = await getProducts().then(res => res.data.data);
      productList.value = res;
      loading.value = false
    }
     */

    //筛选条件
    function _show(event) {
        // _filterForm.value = {...event}
        console.log('筛选条件',event);
        _filterForm.value = event
        // console.log(event);

    }

    //显示详情
    function showDetail(row) {
        // console.log(row.id);
        router.push({ name: 'detail', params: { id: row.id } });
    }

    return {
        _show,
        showDetail,
        pages,
        pageNum,
        total,
        loading,
        productList
    }
}

export const useProductDetail = (id)=>{

    //watch
    const {data:proDetail,loading,run} = useRequest(getProductDetail,{manual:true});
    run(id);


    // onMounted(async ()=>{

    //    let res = await getProductDetail(id).then(res=>res.data.data);
    //    console.log(res);
    //     proDetail.value = res;
    //     console.log(proDetail.value);
    // })

    return {
        proDetail
    }
}
